package com.kk.audioeffect;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.AudioFormat;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.kk.audioeffect.databinding.ActivityMainBinding;
import com.kk.audioeffect.databinding.DialogAudioEffectItemBinding;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private final static String TAG = "MainActivity";

    // Used to load the 'audioeffect' library on application startup.
    static {
        System.loadLibrary("audioeffect");
    }

    private ActivityMainBinding binding;

    PCMPlayer mPcmPlayer = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TasksHelper.getUIHandler().sendEmptyMessage(0);
        TasksHelper.getWorkHandler().sendEmptyMessage(0);

        PermissionManager.getInstance().checkPermission(this, new PermissionManager.Callback() {
            @Override
            public void result(boolean isSuccess) {

            }
        });

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.bassSeek.setMax(300);


        mPcmPlayer = PCMPlayer.create(44100, 2, AudioFormat.ENCODING_PCM_16BIT);

        mPcmPlayer.setFilePath("/sdcard/houlai_s16.pcm");

        mPcmPlayer.setMusicListener(new IMusicListener() {
            @Override
            public void onPrepared(IPlayControl playControl) {
                Log.i(TAG, "onPrepared: ");
                playControl.start();
            }

            @Override
            public void onError(IPlayControl playControl, int error_code) {
                Log.i(TAG, "onError: " + error_code);
            }

            @Override
            public void onCompletionListener(IPlayControl playControl) {

                Log.i(TAG, "onCompletionListener: ");
                playControl.stop();
                playControl.reset();
            }
        });


        initView();

        initListener();


    }

    private float[] mEQZ_BANDS = new float[]{60, 170, 310, 600, 1000, 3000, 6000, 12000, 14000, 16000};


    class ViewHolder {
        DialogAudioEffectItemBinding binding;
        int bandIndex;
    }

    List<ViewHolder> mListViewHolder = new ArrayList<>();

    ArrayAdapter<String> adapterForSpinner;
    List<String> mPresetList = new ArrayList<>();

    private void initView() {

        mPresetList.add("flat");
        mPresetList.add("classical");
        mPresetList.add("club");
        mPresetList.add("dance");
        mPresetList.add("fullbass");
        mPresetList.add("fullbasstreble");
        mPresetList.add("fulltreble");
        mPresetList.add("headphones");
        mPresetList.add("largehall");
        mPresetList.add("live");
        mPresetList.add("party");
        mPresetList.add("pop");
        mPresetList.add("reggae");
        mPresetList.add("rock");
        mPresetList.add("ska");
        mPresetList.add("soft");
        mPresetList.add("ska");
        mPresetList.add("softrock");
        mPresetList.add("techno");

        adapterForSpinner = new ArrayAdapter<>(this, R.layout.dialog_spinner_item, mPresetList);
        binding.spinnerPreset.setAdapter(adapterForSpinner);

        //binding.audioEffect.item1
        for (int i = 0; i < mEQZ_BANDS.length; i++) {
            DialogAudioEffectItemBinding bindingItem = DialogAudioEffectItemBinding.inflate(LayoutInflater.from(this));
            bindingItem.tvHz.setText((int) mEQZ_BANDS[i] + "HZ");
            bindingItem.sbHz.setMax(40);
            binding.audioEffect.controlList.addView(bindingItem.getRoot(), GridLayout.LayoutParams.MATCH_PARENT, GridLayout.LayoutParams.WRAP_CONTENT);

            bindingItem.sbHz.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    int process = seekBar.getProgress();
                    process = process - 20;
                    ViewHolder viewHolder = (ViewHolder) seekBar.getTag();
                    if (viewHolder != null) {
                        viewHolder.binding.tvDB.setText(process + "DB");
                    }
                    Log.i(TAG, "onStopTrackingTouch: " + process);

                    PCMPlayer.native_upate_bands_prem(viewHolder.bandIndex, process);
                }
            });
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.binding = bindingItem;
            viewHolder.bandIndex = i;

            bindingItem.sbHz.setTag(viewHolder);
            mListViewHolder.add(viewHolder);
        }

    }

    private void gotoHome() {
        Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(mHomeIntent);

    }

    private void initListener() {


        //PCMPlayer.native_bass(20.0f);
        binding.btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPcmPlayer.isPause()) {
                    mPcmPlayer.start();
                } else {
                    mPcmPlayer.prepare();
                }


            }
        });


        binding.btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (true) {
                    gotoHome();
                } else {
                    mPcmPlayer.stop();
                }
            }
        });

        binding.bassSeek.setMax(40);
        binding.bassSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                int progress = seekBar.getProgress();
//                if (progress == 0) {
//                    progress = 50;
//                }
                Log.i(TAG, "onStopTrackingTouch: " + progress + "   " + (progress - 20));
                PCMPlayer.native_amp(progress - 20);
            }
        });

        binding.audioEffect.cbEnable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                PCMPlayer.native_init(44100);
            }
        });


        binding.spinnerPreset.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG, "onItemSelected: " + mPresetList.get(position));

                PCMPlayer.native_upate_preset(mPresetList.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    /**
     * A native method that is implemented by the 'audioeffect' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();


    public native void testAudio();
}